package com.shuqi.model.manager;

import android.content.Context;
import android.text.TextUtils;

import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;
import com.shuqi.common.Constant;
import com.shuqi.common.utils.Log4an;
import com.shuqi.database.dao.impl.AccountDao;
import com.shuqi.database.dbimport.OldDBImprotManager;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.WatingListener;
import com.shuqi.model.CheckUserStateOnlineModel;
import com.shuqi.model.CheckUserStateOnlineModel.OnCheckUserStateOnlineListener;
import com.shuqi.model.GetOnlineUserInfoModel;
import com.shuqi.model.GetOnlineUserInfoModel.OnGetOnlineUserInfoListener;
import com.shuqi.model.bean.AccountInfo;
import com.shuqi.model.bean.GetUserOnlineInfo;

/**
 * 账户管理者
 * 
 * @author vip
 */
public class MyAccountManager {
    private static final String logTag = "AccountManager";

    private static UserInfo user;


    /** 获取当前用户信息 */
    public static UserInfo getInstance(Context context) {
        return getInstance(context, false);
    }

    /**
     * 获取当前用户信息
     * 
     * @param context
     * @param isRefresh 从数据库刷新数据
     * @return
     */
    public static UserInfo getInstance(Context context, boolean isRefresh) {
        if (user == null || isRefresh) {
            user = AccountDao.getInstance().getLoginAccount();
            if (isGuestUser(user)) {
                changeGusetUser(context);
            }
        }
        Log4an.e(logTag, (isRefresh?"刷新":"")+"getInstance() 当前用户：" + user.getUserId());
        return user;
    }
    
    /**账户导入数据库完成之后刷新数据*/
    public static void onUserChagedRefreshUserFromDB(Context context){
        getInstance(context, true);
        onUserStateChangeUpdateConfigVersion(context, user);
        Log4an.i(logTag, "onUserChagedRefreshData userId="+user.getUserId());
    }
    
    /***
     * 打开软件检查用户
     * 
     * @param context
     */
    public static void onLoadingCheckUser(Context context, WatingListener watingListener) {
        Log4an.i(logTag, "启动软件，检查用户状态");
        synchronized (MyAccountManager.class) {
            UserInfo user = MyAccountManager.getInstance(context);
            Log4an.i(logTag, "user:"+(user == null?("null"):(user.getUserId() + ",loginState=" + user.getLoginState())));

            if (user == null || TextUtils.isEmpty(user.getUserId())) {
                Log4an.i(logTag, "无用户信息，分配游客身份");
                changeGusetUser(context);
                MyAccountManager.getUserInfoOnline(context, watingListener);
            } else if (isGuestUser(user)) {
                Log4an.i(logTag, "当前为游客身份，联网获取用户信息");
                MyAccountManager.getUserInfoOnline(context, watingListener);
            } else if (isVipUser(user)) {
                Log4an.i(logTag, "会员，开启软件不需要验证用户登录");
                watingListener.onFinish(false);
            } else if (isNeedCheckUserState(user)) {
                Log4an.i(logTag, "已有用户身份，但需要验证用户身份");
                checkUserStateOnline(context, watingListener);
            } else {
                Log4an.i(logTag, "已有用户身份，已验证过用户身份");
                watingListener.onFinish(false);
            }
        }
    }

    /** 在线获取用户身份 */
    public static void getUserInfoOnline(final Context context, final WatingListener watingListener) {
        Log4an.e(logTag, "在线获取用户信息");
        synchronized (MyAccountManager.class) {
            OnGetOnlineUserInfoListener listener = new OnGetOnlineUserInfoListener() {
                @Override
                public void OnFinish(int type, GetUserOnlineInfo info) {// -1，网络失败，0，失败，1成功
                    if (type == GetUserOnlineInfo.RESULT_SUCCESS) {
                        Log4an.e(logTag, "获取用户信息成功,保存当前用户:userid=" + info.getUserId());
                        UserInfo user = new UserInfo();
                        user.setUserId(info.getUserId());
                        user.setSession(info.getSession());
                        user.setNickName(info.getNikeName());
                        user.setGender(info.getGender());
                        user.setBalance(info.getBanlance());
                        user.setUserState(UserInfo.USERSTATE_PASSED);
                        user.setLoginState(UserInfo.LOGINSTATE_LOGINED);
                        onLoginSuccess(context, user);
                        onUserStateChangeUpdateConfigVersion(context, user);
                    } else if (type == GetUserOnlineInfo.RESULT_FAIL_NET) {
                        Log4an.e(logTag, "网络请求失败，切换到游客身份");
                        changeGusetUser(context);
                    } else {
                        Log4an.e(logTag, "获取用户信息失败,切换到游客身份");
                        changeGusetUser(context);
                    }
                    watingListener.onFinish(true);
                }
            };
            GetOnlineUserInfoModel onlineUserInfoModel =
                    new GetOnlineUserInfoModel(context, listener);
            onlineUserInfoModel.loadData();
        }
    }

    /***
     * 在线检查用户身份：完成后回调
     * 
     * @param context
     * @param listener
     */
    public static void checkUserStateOnline(final Context context,
            final WatingListener watingListener) {
        Log4an.e(logTag, " 在线验证用户信息");
        synchronized (MyAccountManager.class) {
            OnCheckUserStateOnlineListener listener = new OnCheckUserStateOnlineListener() {
                @Override
                public void OnFinish(int type, AccountInfo info) {
                    switch (type) {
                        case UserInfo.TYPE_CHECKRESULT_VIPUSER_PASSED:
                            Log4an.e(logTag, "会员验证通过");
                            onCheckUserStatePassed(context, info);
                            break;
                        case UserInfo.TYPE_CHECKRESULT_USER_PASSED:
                            Log4an.e(logTag, "准会员验证通过");
                            onCheckUserStatePassed(context, info);
                            break;
                        case UserInfo.TYPE_CHECKRESULT_USER_PASSED_NEWUSER:
                            Log4an.e(logTag, user.getUserId() + "验证后，分配新userId" + info.getUserId());
                            onCheckUserStatePassed(context, info);
                            break;
                        case UserInfo.TYPE_CHECKRESULT_FAIL:
                            Log4an.e(logTag, "验证失败");
                            changeGusetUser(context);
                            break;
                        case UserInfo.TYPE_CHECKRESULT_FAIL_RECHECK:
                            onCheckUserNeedRecheck(context);
                            Log4an.e(logTag, "验证失败：不更新验证状态，需重下次新验证");
                            break;
                        default:
                            onCheckUserNeedRecheck(context);
                            Log4an.e(logTag, "error type:" + type + ",不更新验证状态，需重下次新验证");
                            break;
                    }
                    watingListener.onFinish(true);
                }
            };
            CheckUserStateOnlineModel userStateOnlineModel =
                    new CheckUserStateOnlineModel(context, listener);
            userStateOnlineModel.checkOnline();
        }
    }

    /** 用户验证：通过后更新用户数据 */
    private static void onCheckUserStatePassed(Context context, AccountInfo info) {
        if (info != null) {
            UserInfo userInfo = info.getUser();
            userInfo.setUserState(UserInfo.USERSTATE_PASSED);
            userInfo.setLoginState(UserInfo.LOGINSTATE_LOGINED);
            onLoginSuccess(context, userInfo);
        }
    }
    /** 用户验证：更新为需要重新验证 */
    private static void onCheckUserNeedRecheck(Context context) {
        user  = getInstance(context, true);
        if(!isGuestUser(user)){
            AccountDao.getInstance().updateUserInfoUserState(user.getUserId(), UserInfo.USERSTATE_UNCHECK);
        }
    }

    /**
     * 当前用户是否已经验证过
     * 
     * @param context
     * @return
     */
    public static boolean isCheckedUserState(UserInfo user) {
        if (user != null && !isGuestUser(user) && user.getUserState() == UserInfo.USERSTATE_PASSED) {
            return true;
        }
        return false;
    }

    /**
     * 当前用户是否需要验证
     * 
     * @param context
     * @return 游客，未验证过的准会员，未验证的会员，需要验证
     */
    public static boolean isNeedCheckUserState(UserInfo user) {
        if (isGuestUser(user)) {
            return true;
        } else if (user.getUserState() != UserInfo.USERSTATE_PASSED) {
            return true;
        }
        return false;
    }


    /**
     * 切换到游客身份状态：8000000
     * 
     * @param context
     * @return
     */
    public static UserInfo changeGusetUser(Context context) {
        Log4an.e(logTag, "切换到游客身份");
        user = new UserInfo();
        user.setUserId(Constant.GUEST_USER_ID);
        user.setLoginState(UserInfo.LOGINSTATE_UNLOGIN);
        AccountDao.getInstance().saveLoginUserInfo(user);
        onUserStateChangeUpdateConfigVersion(context, user);
        return user;
    }

    /***
     * 检查当前用户：是否是正式会员身份
     */
    public static boolean isVipUser(UserInfo user) {
        return user != null
                && !TextUtils.isEmpty(user.getUserId())
                && !Constant.GUEST_USER_ID.equals(user.getUserId())
                && (!TextUtils.isEmpty(user.getEmail()) || !TextUtils.isEmpty(user.getMobile()) || !TextUtils
                        .isEmpty(user.getSinaKey()));
    }
    
    /***
     * 检查当前用户：是否是 邮箱或者手机 正式会员身份
     */
    public static boolean isVipUserByEmailOrMobile(UserInfo user) {
        return user != null
                && !TextUtils.isEmpty(user.getUserId())
                && !Constant.GUEST_USER_ID.equals(user.getUserId())
                && (!TextUtils.isEmpty(user.getEmail()) || !TextUtils.isEmpty(user.getMobile()));
    }
    
    /** 当前用户是否可以阅读、购买 */
    public static boolean isAvailableUser(Context context) {
        
        user = AccountDao.getInstance().getLoginAccount();
        if (isGuestUser(user)) {
            changeGusetUser(context);
        }
        return !isGuestUser(user)&&isCheckedUserState(user);
        
    }

    /**
     * 检查当前用户：是否是游客身份
     */
    public static boolean isGuestUser(UserInfo user) {
        return user == null || TextUtils.isEmpty(user.getUserId())
                || Constant.GUEST_USER_ID.equals(user.getUserId());
    }

    /**
     * 判断是否是准会员
     * 
     * @param user
     * @return
     */
    public static boolean isCommonUser(UserInfo user) {
        return !isGuestUser(user) && !isVipUser(user);
    }

    /**
     * 检查用户的安全级别 <br>
     * UserInfo.USERSAFELEVEL_
     * 
     * @param info
     * @return
     */
    public static int checkUserSafeLevel(UserInfo info) {
        int level = UserInfo.USERSAFELEVEL_LOW;
        int bindNum = 0;
        if (!isGuestUser(info)) {
            if (!TextUtils.isEmpty(info.getEmail())) {
                bindNum++;
            }
            if (!TextUtils.isEmpty(info.getMobile())) {
                bindNum++;
            }
            if (!TextUtils.isEmpty(info.getSinaKey())) {
                bindNum++;
            }
        }
        if (bindNum == 2 || bindNum == 3) {
            level = UserInfo.USERSAFELEVEL_HIGH;
        } else if (bindNum == 1) {
            level = UserInfo.USERSAFELEVEL_COMMON;
        }
        return level;
    }

    /**
     * 新浪微博解绑成功后更新账户信息
     * 
     * @param UserId
     */
    public static boolean onUnBindSinaSuccesee(String userId) {
        Log4an.i(logTag, "解绑新浪微博：" + userId);
        if (isVipUser(user) && !TextUtils.isEmpty(userId) && user.getUserId().equals(userId)) {
            Log4an.i(logTag, "解绑新浪微博：可以解绑账户新浪微博数据");
            return AccountDao.getInstance().updateUsetSinaInfo(userId, "", "", null) > 0;
        }
        Log4an.i(logTag, "解绑新浪微博：解绑账户新浪微博数据：失败");
        return false;
    }

    /***
     * 更新用户资料
     * 
     * @param context
     * @param userInfo
     * @return
     */
    public static boolean onUpdateUserInfo(UserInfo userInfo) {
        Log4an.i(logTag, "更新用户资料");
        if (!isGuestUser(userInfo)) {
            Log4an.i(logTag, "更新用户资料：userId：" + userInfo.getUserId());
            return AccountDao.getInstance().saveUserInfo(userInfo) > 0;
        } else {
            Log4an.i(logTag, "更新用户资料：error 游客身份");
        }
        return false;
    }

    /***
     * 登录成功后
     * 
     * @param context
     * @param userInfo
     * @return
     */
    public static boolean onLoginSuccess(Context context, UserInfo userInfo) {
        Log4an.i(logTag, "登录成功");
        if (userInfo != null && !TextUtils.isEmpty(userInfo.getUserId())
                && !Constant.GUEST_USER_ID.equals(userInfo.getUserId())) {
            userInfo.setLoginState(UserInfo.LOGINSTATE_LOGINED);
            userInfo.setUserState(UserInfo.USERSTATE_PASSED);
            AccountDao.getInstance().saveLoginUserInfo(userInfo);
            onUserChagedRefreshUserFromDB(context);
            return true;
        }
        return false;
    }

    /**
     * 用户改变的时候更新：用户参数
     * 
     * @param context
     * @param userInfo
     */
    public static void onUserStateChangeUpdateConfigVersion(Context context, UserInfo userInfo) {
        ConfigVersion.setTelInfos(context, Config.ROOT_PATH, Config.VERSION_INFO, Config.SOFT_ID,
                Config.MIN_SDK_VERSION, 0, userInfo.getUserId(), userInfo.getSession());
    }

    /***
     * 删除账户数据
     * 
     * @param context
     * @param userId
     * @return
     */
    public static boolean deletUserInfo(Context context, String userId) {
        if (TextUtils.isEmpty(userId)) {
            return false;
        }
        UserInfo userInfo = getInstance(context);
        if (userInfo == null || !userId.equals(userInfo.getUserId())) {
            Log4an.i(logTag, "当前账户：" + userInfo.getUserId() + ",删除账户：" + userId);
            return AccountDao.getInstance().delteUserInfoByUid(userId) > 0;
        } else {
            Log4an.i(logTag, "删除账户失败：" + userId);
        }
        return false;
    }

    /**旧数据库账户导入 from shuqi2.db userinfo*/
    public static boolean importUserInfoFromOldDB(Context context) {
        Log4an.e(logTag, "导入书签和账户数据：开始 ");
        long start = System.currentTimeMillis();
        OldDBImprotManager.getInstance().importDB();
        onUserChagedRefreshUserFromDB(context);
        Log4an.e(logTag, "导入书签和账户数据：结束 "+(System.currentTimeMillis()-start)+" ms");
        return false;
    }

}
